package com.vipheyue.fastlib.xUtils;

import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Types;
import com.orhanobut.logger.Logger;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by heyue on 16/8/4.
 */

public class XUtilsNet {
    public < ResultType>  void post(RequestParams params, final XCallback<ResultType> mCallBack){//Class<T> typeCls
        x.http().post(params, new Callback.CommonCallback<String>() {//xutils3 返回网页的结果为String

            @Override
            public void onSuccess(String result) {
                Logger.d("XUtilsNet  "+result);
                mCallBack.onSuccess((ResultType)new Gson().fromJson(result, mCallBack.mType));//自己的mCallBack返回的类型
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mCallBack.onError(ex,isOnCallback);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    public < ResultType>  void postGetStr(RequestParams params, final XCallback<ResultType> mCallBack){//Class<T> typeCls
        x.http().post(params, new Callback.CommonCallback<String>() {//xutils3 返回网页的结果为String

            @Override
            public void onSuccess(String result) {
                mCallBack.onSuccess((ResultType)result);//自己的mCallBack返回的类型
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mCallBack.onError(ex,isOnCallback);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public static abstract class XCallback<ResultType>//Class<T> typeCls 因为少得到type 好像传Type.class 不行
    {
        Type mType;

        public XCallback()
        {
            mType = getSuperclassTypeParameter(getClass());
        }

        static Type getSuperclassTypeParameter(Class<?> subclass)
        {
            Type superclass = subclass.getGenericSuperclass();
            if (superclass instanceof Class)
            {
                throw new RuntimeException("Missing type parameter.");
            }
            ParameterizedType parameterized = (ParameterizedType) superclass;
            return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
        }
        public abstract void onError(Throwable ex, boolean isOnCallback);

        public abstract void onSuccess(ResultType bean);
    }

}
